﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class SelectSale : CCSkinMain
    {
        private List<Sale> saleList = new List<Sale>();
        public Sale SelectedSale { get; private set; }

        public SelectSale()
        {
            InitializeComponent();
            InitializeForm();
            SetFormIcon();
        }
        /// <summary>
        /// 设置窗体图标
        /// </summary>
        private void SetFormIcon()
        {

            string[] possiblePaths = {
                    System.IO.Path.Combine(Application.StartupPath, "..", "..", "Images", "qq.ico")
                };

            string iconPath = possiblePaths.FirstOrDefault(System.IO.File.Exists);
            if (!string.IsNullOrEmpty(iconPath))
            {
                this.Icon = new System.Drawing.Icon(iconPath);
            }

        }
        private async void InitializeForm()
        {
            this.Text = "销售单选择";
            this.Size = new Size(1000, 700);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 加载销售订单数据
            await LoadSaleData();
        }

        /// <summary>
        /// 加载销售订单数据
        /// </summary>
        private async Task LoadSaleData()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync("http://10.223.8.6:3530/api/SaleOrder/GetSaleOrder");
                    response.EnsureSuccessStatusCode();
                    var jsonResponse = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<SaleApiResponse>(jsonResponse);
                    
                    if (apiResponse?.code == 200 && apiResponse.data != null)
                    {
                        saleList = apiResponse.data.Select(s => new Sale
                        {
                            SalesOrderId = s.SalesOrderId,
                            SalesOrderCode = s.SalesOrderCode,
                            ContractId = s.ContractId,
                            ContractCode = s.ContractCode,
                            ContractName = s.ContractName,
                            ClientId = s.ClientId,
                            ClientCode = s.ClientCode,
                            ClientName = s.ClientName,
                            CTypeId = s.CTypeId,
                            SaleNumder = s.SaleNumder
                        }).ToList();
                        
                        LoadSaleDataToGrid();
                    }
                    else
                    {
                        ShowAlert(string.Format("加载销售订单数据失败: {0}", apiResponse != null ? apiResponse.msg : ""), "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                ShowAlert(string.Format("加载销售订单数据异常: {0}", ex.Message), "错误");
            }
        }

        /// <summary>
        /// 将销售订单数据加载到DataGridView
        /// </summary>
        private void LoadSaleDataToGrid()
        {
            try
            {
                if (saleList == null || saleList.Count == 0)
                {
                    ShowAlert("暂无销售订单数据", "提示");
                    return;
                }

                // 绑定数据到DataGridView
                dgvSales.AutoGenerateColumns = false;
                dgvSales.DataSource = saleList;
                
                Console.WriteLine(string.Format("成功加载 {0} 条销售订单数据", saleList.Count));
            }
            catch (Exception ex)
            {
                ShowAlert(string.Format("加载销售订单数据到表格失败: {0}", ex.Message), "错误");
            }
        }

        /// <summary>
        /// 确认选择
        /// </summary>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (dgvSales.CurrentRow != null)
            {
                var selectedIndex = dgvSales.CurrentRow.Index;
                if (selectedIndex >= 0 && selectedIndex < saleList.Count)
                {
                    SelectedSale = saleList[selectedIndex];
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    ShowAlert("请选择一条销售订单记录", "提示");
                }
            }
            else
            {
                ShowAlert("请选择一条销售订单记录", "提示");
            }
        }

        /// <summary>
        /// 取消选择
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

      

        /// <summary>
        /// 显示提示信息
        /// </summary>
        private void ShowAlert(string message, string caption)
        {
            MessageBox.Show(message, caption, MessageBoxButtons.OK, 
                caption == "成功" ? MessageBoxIcon.Information 
                : caption == "提示" ? MessageBoxIcon.Information 
                : MessageBoxIcon.Error);
        }

        private void dgvSales_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
